package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.domain.dto.AdminLoginDto;
import org.example.domain.entity.Admin;
import org.example.domain.model.Result;
import org.example.mapper.AdminLoginMapper;
import org.example.service.IAdminLoginService;
import org.example.util.FmBackendJwtUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminLoginServiceImpl implements IAdminLoginService {

    private AdminLoginMapper adminLoginMapper;
    private PasswordEncoder passwordEncoder;
    private FmBackendJwtUtils fmBackendJwtUtils;
    private Log log = LogFactory.getLog(AdminLoginServiceImpl.class);

    public AdminLoginServiceImpl(AdminLoginMapper adminLoginMapper, PasswordEncoder passwordEncoder, FmBackendJwtUtils fmBackendJwtUtils) {
        this.adminLoginMapper = adminLoginMapper;
        this.passwordEncoder = passwordEncoder;
        this.fmBackendJwtUtils = fmBackendJwtUtils;
    }

    @Override
    public Result adminlogin(AdminLoginDto adminLoginDto) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",adminLoginDto.getUsername());
        Admin admin = adminLoginMapper.selectOne(queryWrapper);

        if(admin == null || !passwordEncoder.matches(adminLoginDto.getPassword(),admin.getPassword())){
            return Result.buildFail("用户名或密码不正确");
        }else {
            Map<String ,String> tokens=new HashMap<>();
            String username=adminLoginDto.getUsername();
            tokens.put(FmBackendJwtUtils.ACCESS_TOKEN_KEY,fmBackendJwtUtils.createAccessToken(username));
            tokens.put(FmBackendJwtUtils.REFRESH_TOKEN_KEY,fmBackendJwtUtils.createRefreshToken(username));
            return Result.buildSuccess(tokens);
        }
    }
}
